package org.itboys.weixin.controller;

import com.google.common.collect.Maps;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.weixin.entity.WeixinConfig;
import org.itboys.weixin.entity.WeixinMenu;
import org.itboys.weixin.service.WeixinConfigService;
import org.itboys.weixin.service.WeixinMenuService;
import org.itboys.weixin.tools.WeixinMenuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名：com.hz.sunday.xlcl.controller.web
 * 作者 : 江雄
 * Email: empty90911@126.com
 * 时间：2015年10月8日 下午3:47:21
 * 描述:圣代_微信菜单_controller_web
 *
 */

@Controller
@RequestMapping("/sunday/web/weixin/menu")
public class SundayWeiXinMenuController extends BaseController {

    @Autowired
    private WeixinMenuService weixinMenuService;
    @Autowired
    private WeixinConfigService weixinConfigService;
    /**
     * 微信菜单主页
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/index")
    public String index(
            HttpServletRequest request,
            @RequestParam(value="weixinId",required=true)Long weixinId,
            Model model){
        model.addAttribute("weixinId",weixinId);

        return "/sunday/weixin/menu/index";
    }

    /**
     * 获取微信菜单，以树结构的形式
     * @param response
     * @param request
     */
    @RequestMapping("/getTree")
    public void getTree(HttpServletResponse response,
                        HttpServletRequest request,
                        @RequestParam(value="weixinId",required=true)Long weixinId){
        try {
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("isDeleted",0);
            param.put("weixinId",weixinId);
            param.put("orderByKey","sort");
            List<WeixinMenu> menus = weixinMenuService.list(param);
            List<Map<String,Object>> parents = new ArrayList<Map<String,Object>>();
            List<Map<String,Object>> childs = new ArrayList<Map<String,Object>>();
            for(WeixinMenu menu:menus){
                Map<String, Object> m =new HashMap<String,Object>();
                m.put("id",menu.getId());
                m.put("parentId",menu.getParentId());
                m.put("name",menu.getName());
                m.put("type",menu.getType());
                m.put("value",menu.getValue());
                m.put("sort",menu.getSort());
                m.put("expanded",false);
                if(menu.getParentId()==0l){
                    m.put("children",null);
                    parents.add(m);
                }else{
                    childs.add(m);
                }
            }
            for(Map<String,Object> parent:parents){
                Long id  = Long.valueOf(parent.get("id").toString());
                List<Map<String,Object>> children = new ArrayList<Map<String,Object>>();

                for(Map<String,Object> child:childs){
                    Long parentId = Long.valueOf(child.get("parentId").toString());
                    if(parentId.longValue()==id.longValue()){
                        children.add(child);
                    }
                }
                if(ListUtil.isNotNull(children)){
                    parent.put("expanded",true);
                }
                parent.put("children",children);
            }

            AjaxUtils.renderJson(response, parents);
        } catch (Exception e) {
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE, CommonConstants.FAIL));
        }
        Map<String, Object> param =new HashMap<String,Object>();

        List<WeixinMenu> list = weixinMenuService.list(param);
        for(WeixinMenu wm:list){
            if(wm.getType()== WeixinMenu.TYPE_PARENT){
                param.clear();
                param.put("parentId", Long.valueOf(wm.getId()));
                wm.setChildNum(weixinMenuService.count(param));
            }
        }
        JsonPageUtils.renderJsonPage(list!=null&&list.size()>0?list.size():0L, list, response);
    }
    /**
     * 查询当个菜单
     * @param request
     * @param response
     * @param id
     */
    @RequestMapping("/findOne")
    public void findOne(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value="id",required=true)Long id){
        try {
            WeixinMenu menu = weixinMenuService.getById(id);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgResultDO(menu, CommonConstants.SUCCESS));
        } catch (Exception e) {
            logger.error("/sunday/weixin/menu/findOne------"+e.getMessage());
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,  CommonConstants.ERROMSG));
        }
    }

    /**
     * 新增或编辑微信菜单
     * @param response
     * @param weixinMenu
     */
    @RequestMapping("/save")
    public void save(HttpServletResponse response,
                     @ModelAttribute WeixinMenu weixinMenu) {
        try {
            if (weixinMenu.getId() == 0L) {
                if(!LongUtil.isNotZreo(weixinMenu.getParentId()))weixinMenu.setParentId(0l);
                weixinMenuService.save(weixinMenu);
            } else {
                weixinMenuService.update(weixinMenu);
            }
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getErrorResultDO(CommonConstants.SUCCESS_CODE,  CommonConstants.ERROMSG));
        } catch (Exception e) {
            logger.error("/sunday/weixin/menu/save------"+e.getMessage());
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,  CommonConstants.ERROMSG));
        }
    }

    /**
     * 删除微信菜单
     * @param response
     * @param request
     * @param id
     */
    @RequestMapping("/delete")
    public void delete(HttpServletResponse response,HttpServletRequest request,
                       @RequestParam(value="id",required=true)Long id){
        try{
            //Long id =  Long.valueOf(request.getParameter("id"));
            weixinMenuService.delete(id);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getErrorResultDO(CommonConstants.SUCCESS_CODE,  CommonConstants.ERROMSG));
        } catch (Exception e) {
            logger.error("/sunday/weixin/menu/delete------"+e.getMessage());
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,  CommonConstants.ERROMSG));
        }
    }

    /**
     * 同步微信菜单
     * @param response
     * @param request
     * @param weixinId
     */
    @RequestMapping("/doCreateWeixinMenu")
    public void doCreateWeixinMenu(HttpServletResponse response,HttpServletRequest request,
                                   @RequestParam(value="weixinId",required=true)Long weixinId){
        try{
            //Long weixinId=Long.valueOf(request.getParameter("weixinId"));
            WeixinConfig wc=weixinConfigService.getById(Long.valueOf(weixinId));
            Map<String, Object> param = Maps.newHashMapWithExpectedSize(1);
            param.put("weixinId", weixinId);
            param.put("isDeleted",0);
            List<WeixinMenu> list = weixinMenuService.list(param);
            WeixinMenuUtils.doCreateWeixinMenu(wc.getAppId(), wc.getAppSecret(), list);
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.SUCCESS_CODE,  CommonConstants.SUCCESS));
        } catch (Exception e) {
            logger.error("/sunday/weixin/menu/doCreateWeixinMenu------"+e.getMessage());
            e.printStackTrace();
            AjaxUtils.renderJsonporJson(response, null,
                    ResultPageDOHelper.getMsgCodeResultDO(CommonConstants.FAIL_CODE,  CommonConstants.ERROMSG));
        }
    }

}
